'use strict';
const uniAccount = require('uni-account')
const db = uniCloud.database();
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const type = event.type; 
	if (type == "phone") { //手机号注册
		let result = await db.collection('user').where({
			phone: event.phone
		}).get() 
		if (result.affectedDocs) { //已经注册
			return result.data[0]._id
		} else { //这里他返回有id
			
			let res = await db.collection('user').add({
				phone: event.phone,
				name: event.phone,
				atr:event.atr,
				vip: 0,
				admin:0
			})
			return res.id
		}
	} 
	else { //微信登录
		const appId = "wxb639839c002f8f15";
		const secret = "24643b7b4c42d4da2d18e660be8ecb1d"
		const uniAccountIns = uniAccount.initWeixin({
			appId,
			secret
		})
		let {openid} = await uniAccountIns.code2Session(event.code)
		let result = await db.collection('user').where({
			wxId: openid
		}).get()
		if (result.affectedDocs) { //已经注册
			return result.data[0]._id
		} else {
			let res =  await db.collection('user').add({
				wxId: openid,
				atr: event.atr,
				name: event.name,
				vip: 0,
				admin:0
			})
			return res.id
		}
	}
};
